package filter;

import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;

import itcast.domain.User;
import sun.awt.RepaintArea;


/**
 * 完成登录验证的过滤器
 * 
 */
//@WebFilter("/*")
public class loginfilter implements Filter {

    /**
     * Default constructor. 
     */
    public loginfilter() {
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see Filter#destroy()
	 */
	public void destroy() {
		// TODO Auto-generated method stub
	}

	/**
	 * @see Filter#doFilter(ServletRequest, ServletResponse, FilterChain)
	 */
	public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws IOException, ServletException {
		//1、强制转换
		HttpServletRequest request =(HttpServletRequest)req;
		
		//1、获取登录相关的路径，如果是登录相关的页面直接放行
		//1、获取资源路径
		String uri=request.getRequestURI();
		//2、如果包含的有登录相关的资源路径放行，注册也放行！
		if (uri.contains("/login.jsp") || uri.contains("/loginServlet") || uri.contains("/css/") ||
				uri.contains("/js/") || uri.contains("/fonts/")|| uri.contains("/fcheckcodeServlet")||
				uri.contains("/Register.jsp") || uri.contains("/addUserServlet")) {
			//包含了就是用户点击了登录相关，直接放行
			chain.doFilter(req, resp);
		}else {
			//用户点击了不包含登录的页面，则应该提示用户应该登录
			//用session来判断
			Object testuser=request.getSession().getAttribute("user");
			if (testuser !=null) {
				//判断不为空就是从loginServlet获取了对象，已经登录，放行
				chain.doFilter(req, resp);
			}else {
				//没有登录则跳转到登录页面
				request.setAttribute("lose", "你还没有登录，先登录一下吧！");
				request.getRequestDispatcher("/login.jsp").forward(request, resp);
			}
			
		}
		
		
		
		//放行代码
		//chain.doFilter(request, response);
	}

	/**
	 * @see Filter#init(FilterConfig)
	 */
	public void init(FilterConfig fConfig) throws ServletException {
		// TODO Auto-generated method stub
	}

}
